package site.addzero.cli.autoinit.common

import org.koin.core.annotation.Single
import site.addzero.cli.platform.PlatformTools
import site.addzero.cli.platform.PlatformType
import site.addzero.cli.platform.runCmd
import site.addzero.cli.setting.SettingContext
import site.addzero.task.InitTask
import java.io.File

/**
 * 环境脚本自动初始化类
 * 负责在不同平台上执行相应的环境初始化脚本
 */
@Single
class AutoInitEnvironmentScripts : InitTask {
    override val support: Boolean = true

    /**
     * 执行环境脚本初始化任务
     */
    override suspend fun asynctask(): Boolean {
        val platformType = PlatformTools.getPlatformType()

        return when (platformType) {
            PlatformType.WINDOWS -> initializeWindowsScripts()
            PlatformType.MACOS, PlatformType.LINUX -> initializeUnixScripts()
            else -> {
                println("Unsupported platform for environment script initialization")
                false
            }
        }
    }

    /**
     * 初始化 Windows PowerShell 脚本
     */
    private fun initializeWindowsScripts(): Boolean {
        val resourceDir = getResourceDirectory()

        if (resourceDir == null) {
            println("无法找到资源目录")
            return false
        }

        val winScriptDir = File(resourceDir, "win")
        if (!winScriptDir.exists() || !winScriptDir.isDirectory) {
            println("Windows脚本目录不存在: ${winScriptDir.absolutePath}")
            return false
        }

        // 获取所有.ps1文件并执行
        val ps1Files = winScriptDir.listFiles { file ->
            file.extension.equals("ps1", ignoreCase = true)
        }

        if (ps1Files.isNullOrEmpty()) {
            println("Windows脚本目录中没有找到.ps1文件")
            return false
        }

        var success = true
        for (scriptFile in ps1Files) {
            println("执行Windows PowerShell脚本: ${scriptFile.name}")
            val command = "powershell -ExecutionPolicy Bypass -File \"${scriptFile.absolutePath}\""
            val result = command.runCmd()

            if (result.isSuccess()) {
                println("成功执行脚本: ${scriptFile.name}")
            } else {
                println("执行脚本失败: ${scriptFile.name}, 错误: ${result.error}")
                success = false
            }
        }
        
        return success
    }

    /**
     * 初始化 Unix 脚本 (macOS/Linux)
     */
    private fun initializeUnixScripts(): Boolean {
        val resourceDir = getResourceDirectory()

        if (resourceDir == null) {
            println("无法找到资源目录")
            return false
        }

        val unixScriptDir = File(resourceDir, "unix")
        if (!unixScriptDir.exists() || !unixScriptDir.isDirectory) {
            println("Unix脚本目录不存在: ${unixScriptDir.absolutePath}")
            return false
        }

        // 获取所有.sh文件并执行
        val shFiles = unixScriptDir.listFiles { file ->
            file.extension.equals("sh", ignoreCase = true)
        }

        if (shFiles.isNullOrEmpty()) {
            println("Unix脚本目录中没有找到.sh文件")
            return false
        }

        var success = true
        for (scriptFile in shFiles) {
            println("执行Unix脚本: ${scriptFile.name}")
            val command = "source \"${scriptFile.absolutePath}\""
            val result = command.runCmd()

            if (result.isSuccess()) {
                println("成功执行脚本: ${scriptFile.name}")
            } else {
                println("执行脚本失败: ${scriptFile.name}, 错误: ${result.error}")
                success = false
            }
        }
        
        return success
    }

    /**
     * 获取资源目录
     */
    private fun getResourceDirectory(): File? {
        // 尝试多种可能的资源目录路径
        val possiblePaths = listOf(
            "src/main/resources",  // 开发时路径
            "resources"            // 运行时可能的路径
        )

        for (path in possiblePaths) {
            val file = File(SettingContext.HOME_DIR, path)
            if (file.exists() && file.isDirectory) {
                return file
            }

            val absoluteFile = File(path)
            if (absoluteFile.exists() && absoluteFile.isDirectory) {
                return absoluteFile
            }
        }

        // 如果相对路径找不到，尝试从classpath获取
        val classLoader = this::class.java.classLoader
        val resource = classLoader.getResource("")
        if (resource != null) {
            return File(resource.toURI())
        }

        return null
    }
}
